package com.wangjie.diffarray;

/**
 * @author jieshao
 * @date 2022/4/2 11:44
 */
public class Difference {
    // 差分数组
    private int[] diff;

    // 构造差分数组
    public Difference(int[] num) {
        diff = new int[num.length];
        diff[0] = num[0];
        for (int i = 1; i < num.length; i++) {
            diff[i] = num[i] - num[i - 1];
        }
    }

    // 给闭区间 [i, j] 增加 val(可以是负数)
    public void increment(int i, int j, int val) {
        diff[i] += val;
        if (j + 1 < diff.length) {
            diff[j + 1] -= val;
        }
    }

    // 返回结果数组
    public int[] result() {
        int[] res = new int[diff.length];
        res[0] = diff[0];
        for (int i = 1; i < diff.length; i++) {
            res[i] = res[i - 1] + diff[i];
        }
        return res;
    }
}